/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* 
 * File:   UdpPacket.cpp
 * Author: everpan
 * 
 * Created on 2018年11月6日, 下午10:08
 */

#include "UdpPacket.h"
namespace pr {

    UdpPacket::UdpPacket() {
    }

    UdpPacket::UdpPacket(const UdpPacket& orig) {
    }

    UdpPacket::~UdpPacket() {
        _data = nullptr;
        _head = nullptr;
        _len = 0;
    }

    u32_t UdpPacket::Head::getPackageNo() {
        return From4ByteToU32(pno);
    }

    u32_t UdpPacket::Head::getBodyLength() {
        return From2ByteToU32(len);
    }

    u64 UdpPacket::Head::getTime() {
        //ret val must be cache
        return TIMESTAMP_2000 + From4ByteToU32(date);
    }

    u8_t UdpPacket::Head::getSNo() {
        return sno;
    }

    u8_t UdpPacket::Head::getVer() const {
        return ver;
    }

    u32_t UdpPacket::TGN::getTagId() {
        return From3ByteToU32(tagId);
    }

    float UdpPacket::TGN::getValue() {
        u32_t ui = From4ByteToU32(tagVal);
        return *(float*) (&ui);
    }

    char UdpPacket::TGN::getQuality() {
        return quality;
    }

    void UdpPacket::setData(u8_t* data, int len) {
        _data = data;
        _len = len;
        _package_count = 0;
        _head = (Head *) _data;
        if (isValid()) {

        }
    }

    u16_t UdpPacket::getCmd() {
        return _head->cmd;
    }

    UdpPacket::Head * UdpPacket::getHead() {
        return _head;
    }

    UdpPacket::TGN * UdpPacket::getTGN() {
        return (TGN*) (_data + sizeof (Head));
    }

    bool UdpPacket::isValid() {
        if (!_isValid) {
            do {
                if (_data == nullptr) break;
                if (_len < sizeof (UdpPacket::Head)) break;
                if (_data[0] == 'P' && _data[1] == 'R') {
                    _isValid = true;
                    break;
                }
            } while (0);
        }
        return _isValid;
    }

//    bool UdpPacket::hasNext() {
//
//    }

    u32_t UdpPacket::getNum() {
        if (_package_count == 0) {
            if (_head->cmd == 1) {
                _package_count = _head->getBodyLength() / sizeof (TGN);
            } else {
                //其余待实现
            }
        }
        return _package_count;
    }
}

